package org.grow.cooldown.ScoreModule;

import org.springframework.stereotype.Service;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Service
public class HolderIntercepter implements HandlerInterceptor {

    private static ThreadLocal<String> threadLocal = new ThreadLocal();
    public static void setTitle(String title){
        threadLocal.set(title);
    }
    public static String getTitle(){
        return threadLocal.get();
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String s ="hold url : "+request.getRequestURI();
        this.setTitle(s);
        System.err.println(Thread.currentThread().getName()+" Pre == >>>"+this.getTitle());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //如果访问两个不同请求 导致这里打印不同 就表明了threadLocal实现了容器单例bean关联线程多例bean
        //此处bean只是个string而已
        System.err.println(Thread.currentThread().getName()+" Post == >>>"+this.getTitle());

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        threadLocal.remove();
    }
}
